from rest_framework_simplejwt.views import TokenObtainPairView
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.renderers import JSONRenderer


class CustomTokenObtainPairView(TokenObtainPairView):
    """
    自定义Token获取视图，明确禁止GET方法
    """
    def get(self, request, *args, **kwargs):
        """
        禁止使用GET方法访问登录接口
        """
        return Response(
            {'detail': '方法 “GET” 不被允许。'},
            status=status.HTTP_405_METHOD_NOT_ALLOWED
        )
    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        try:
            serializer.is_valid(raise_exception=True)
        except Exception as e:
            return Response({"error": "Invalid credentials"}, status=400)

        response = Response({
            'access': serializer.validated_data['access'],
            'refresh': serializer.validated_data['refresh'],
            'user': {
                'id': serializer.user.id,
                'username': serializer.user.username
            }
        })
        
        # 确保响应使用JSON格式
        response.accepted_renderer = JSONRenderer()
        response.accepted_media_type = 'application/json'
        response.renderer_context = {'view': self}
        return response
